package com.atguigu.tingshu.payment.api;

import com.atguigu.tingshu.common.Login.TsLogin;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.atguigu.tingshu.payment.service.WxPayService;
import com.wechat.pay.java.service.payments.model.Transaction;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Tag(name = "微信支付接口")
@RestController
@RequestMapping("api/payment/wxPay")
@Slf4j
public class WxPayApiController {
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private PaymentInfoService paymentInfoService;

    /**
     * 微信下单支付
     * @param paymentType
     * @param orderNo
     * @return
     */
    @Operation(summary = "微信下单支付")
    @TsLogin
    @PostMapping("/createJsapi/{paymentType}/{orderNo}")
    public Result createJsapi(@PathVariable String paymentType,@PathVariable String orderNo ){
        Long userId = AuthContextHolder.getUserId();
        //  调用微信支付方法
        Map map =wxPayService.createJsapi(paymentType,orderNo,userId);
        return Result.ok(map);
    }

    /**
     * 查询支付状态 https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_5_2.shtml
     * @param orderNo
     * @return
     */
    @Operation(summary = "支付状态查询")
    @GetMapping("/queryPayStatus/{orderNo}")
    public Result queryPayStatus(@PathVariable String orderNo) {
        //调用服务层方法
        Transaction transaction=wxPayService.queryPayStatus(orderNo);
        //判断返回结果 成功或失败
        if (null != transaction && transaction.getTradeState().equals(Transaction.TradeStateEnum.SUCCESS)) {
            //说明这个用户支付成功了 返回true 更新交易记录状态
            paymentInfoService.updatePaymentStatus(transaction);
            return Result.ok(true);
        }
        //说明这个用户支付失败了 返回true
        return Result.ok(false);
    }


    /**
     * 异步回调 微信-》商户 需要内网穿透 确保外部微信可访问内部局域网接口  配置bootstrap.properties的wechat.v3pay.notifyUrl
     * 通知频次率为15s/15s/30s/3m/10m/20m/30m/30m/30m/60m/3h/3h/3h/6h/6h - 总计 24h4m 15次
     * 支付宝8次通知
     * https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_5_5.shtml
     * @param request
     * @return
     */
    @Operation(summary = "微信支付异步通知接口")
    @PostMapping("/notify")
    public Map<String,Object> wxNotify(HttpServletRequest request){
        Map<String,Object> result = new HashMap<>();
        try {
            //  调用方法
            wxPayService.wxnotify(request);
            //返回成功
            result.put("code", "SUCCESS");
            result.put("message", "成功");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }

        //返回失败
        result.put("code", "FAIL");
        result.put("message", "失败");
        return result;
    }

    /**
     * 微信Native下单
     * @param paymentType
     * @param orderNo
     * @return
     */
    @TsLogin
    @Operation(summary = "微信Native下单")
    @Parameters({
            @Parameter(name = "paymentType",description = "支付类型：1301-订单 1302-充值",in = ParameterIn.PATH,required = true),
            @Parameter(name = "orderNo",description = "订单号",required = true,in = ParameterIn.PATH),
    })
    @PostMapping("/createNative/{paymentType}/{orderNo}")
    public Result<Map<String, Object>> createNative(@PathVariable String paymentType, @PathVariable String orderNo) {
        Map<String, Object> map = wxPayService.createNative(paymentType, orderNo, AuthContextHolder.getUserId());
        return Result.ok(map);
    }

    /**
     * 关闭交易记录
     * 1、关闭本地交易记录
     * 2、关闭微信交易记录
     * @param orderNo
     * @return
     */
    @Operation(summary = "关闭交易记录")
    @GetMapping("/closePayment/{orderNo}")
    public Result closePayment(@PathVariable String orderNo){
        //  调用服务层方法.
        boolean flag = this.paymentInfoService.closePayment(orderNo);
        //  返回结果
        return Result.ok(flag);
    }

    /**
     * 退款
     * @param orderNo
     * @return
     */
    @Operation(summary = "退款")
    @GetMapping("/refund/{orderNo}")
    public Result refund(@PathVariable String orderNo){
        //  调用服务层方法.
        boolean flag = this.wxPayService.refund(orderNo);
        //  返回结果
        return Result.ok(flag);
    }
}
